<template>
  <div>
    <el-dialog
      :model-value="openPrice"
      :close-on-click-modal="false"
      title="价格详情"
      append-to-body
      :before-close="handelClose"
    >
      <custom-container ref="customContainerRef" :config="mainConfig" />
      <!-- 新增价格详情 -->
   
      <!-- 价格guan -->
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  getCurrentInstance,
  defineAsyncComponent,
  computed,
} from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElSwitch } from 'element-plus'
import { getcostList, getcostDetail, addCostManagement, editCostManagement, delCostManagement } from '@/api/BusinessConfig/costPriceManagement'

const props = defineProps({
  idPrice: {
    type: Number,
  },
  openPrice: {
    type: Boolean,
  },
})
const emit = defineEmits(['update:openPrice', 'update:modelValue'])
const
  queryParams = ref({
    pageSize: 10,
    pageNum: 1,
    costPriceId: undefined,
  }),
  openPriceManage = ref(false),
  priceManageTitle = ref(''),
  costManageDetail = ref({
    id: undefined,
    costPriceId: undefined,
    openingDate: undefined,
    obsoleteDate: undefined,
    remarks: undefined,
  }),
  pricrManageRules = {
    status: [{ required: true, message: '必填', trigger: 'blur' }],
    openingDate: [{
      required: true,
      message: '生效日期必须选择',
      trigger: ['change', 'blur'],
    }],
    obsoleteDate: [{
      required: true,
      message: '生效日期必须选择',
      trigger: ['change', 'blur'],
    }],
    receivingSite: [{ required: true, message: '必填', trigger: 'blur' }],
  },
  customContainerRef = ref(null),
  priceManageFormRef = ref(null),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()
const reset = () => {
  costManageDetail.value = {
    id: undefined,
    costPriceId: undefined,
    openingDate: undefined,
    obsoleteDate: undefined,
    remarks: undefined,
  }
  proxy.$resetForm(priceManageFormRef.value)
} 
const handleQuery = () => {
  customContainerRef.value.getList()
}
const handelClose = () => {
  emit('update:openPrice', false)
}
// 新增价格详情
const handleAdd = () => {
  openPriceManage.value = true
  priceManageTitle.value = '新增价格详情'
}
// 修改价格详情
const handleUpdate = (row: { [key: string]: any }) => {
  openPriceManage.value = true
  priceManageTitle.value = '修改价格详情'
  getcostDetail(row.id).then(res => {
    costManageDetail.value = res.data
  })
}
// 确定新增--修改
const submitPriceManage = () => {
  proxy.$validateForm(priceManageFormRef.value, () => {
    costManageDetail.value.costPriceId = props.idPrice
    if (priceManageTitle.value.includes('修改')) {
      editCostManagement(costManageDetail.value).then(res => {
        reset()
        openPriceManage.value = false
        res.code === 200 && ElMessage.success('修改成功')
        handleQuery()
      })
    } else {
      addCostManagement(costManageDetail.value).then(res => {
        reset()
        openPriceManage.value = false
        res.code === 200 && ElMessage.success('新增成功')
        handleQuery()
      })
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 取消新增、修改
const cancelPriceManage = () => {
  reset()
  openPriceManage.value = false
}
// 删除价格详情
const handleDelete = (row:{[key:string]:any}) => {
  const id = (row && row.id)
  ElMessageBox.confirm(`"是否确定删除价格编号为"${ id }"的数据?"`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delCostManagement(id).then(res => {
      res.code === 200 && ElMessage.success('删除成功')
      handleQuery()
    })
  })
  .catch(error => {
    if (error == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 修改价格详情状态
const handleStatusChange = (row: { [key: string]: any }) => {
  const text = row.status == 1 ? '停用' : '启用'
  row.status = row.status === 0 ? 1 : 0
  const data = { id: row.id, status: row.status }
  ElMessageBox.confirm(`确认要"${ text }"编号为"${ row.id }"的状态吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => editCostManagement(data))
  .then((res) => {
    if (res.code == 200) {
      ElMessage.success(`${ text }成功`)
      handleQuery()
    } 
  })
  .catch((error) => {
    if (error === 'cancel') {
      ElMessage.info('取消操作')
      handleQuery()
    }
  })
}
// 修改价格
const mainConfig = computed({
  get() {
    return {
      query: {
        fields: [],
        queryParams: queryParams.value,
      },
      btns: [
        {
          title: '新增',
          type: 'primary',
          onClick: handleAdd,
        },
      ],
      table: {
        columns: [
          {
            label: '状态',
            prop: 'status',
            align: 'center',
            render(h, params) {
              return h(ElSwitch, {
                onChange: () => {
                  handleStatusChange(params.row)
                  console.log('handleStatusChange', params)
                },
                modelValue: params.row.status,
                'onUpdate:modelValue': (value) => {
                  emit('update:modelValue', value)
                },
                activeValue: 0,
                inactiveValue: 1,
                activeColor: '#C0CCDA',
                inactiveColor: '#409EFF',
              })
            },
          },
          {
            label: '生效日期',
            prop: 'openingDate',
            align: 'center',
          },
          {
            label: '失效日期',
            prop: 'obsoleteDate',
            align: 'center',
          },
          {
            label: '备注',
            prop: 'remarks',
            align: 'center',
          },
          {
            label: '操作',
            align: 'center',
            showOverflowTooltip: false,
            width: 200,
            render: (h, params) => {
              const buttons = [
                {
                  title: '修改',
                  clickFun: handleUpdate,
                },
                {
                  title: '删除',
                  
                  clickFun: handleDelete,
                },
                {
                  title: '价格管理',
                  
                  // clickFun: handlePriceManagement,
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  icon: el.icon,
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
  
        ],
      },
      api: getcostList,
      requestTrans: (q: { pageNum: number; pageSize: number; costPriceId: any }) => {
        q.costPriceId = props.idPrice
        queryParams.value = q
        return q
      },
    }
  },
  set(val) {
    return val
  },
})
</script>